package com.qiumo.gmtool.config;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiumo.gmtool.entity.UserAuthEntity;
import com.qiumo.gmtool.entity.UserEntity;
import com.qiumo.gmtool.service.UserAuthService;
import com.qiumo.gmtool.service.UserService;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户权限配置
 */
@Component
@RequiredArgsConstructor
public class UserPermission implements StpInterface {

    private final UserService userService;

    private final UserAuthService userAuthService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        UserEntity one = userService.getOne(new LambdaQueryWrapper<UserEntity>()
            .eq(UserEntity::getUid, loginId));
        if (one.getRole().equals("SUPERADMIN") || one.getRole().equals("ADMIN")) {
            return Arrays.asList("*");
        }
        List<UserAuthEntity> list = userAuthService.getAllPermByUid(String.valueOf(loginId));
        List<String> collect = Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(li -> {
            return li.getAuthName();
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        UserEntity one = userService.getOne(new LambdaQueryWrapper<UserEntity>()
            .eq(UserEntity::getUid, loginId));
        return Arrays.asList(one.getRole());
    }
}
